package com.google.code.gerp.security

import org.apache.commons.lang.builder.HashCodeBuilder

class PrincipalGroup implements Serializable {

	Principal principal
	Group group

	boolean equals(other) {
		if (!(other instanceof PrincipalGroup)) {
			return false
		}

		other.principal?.id == principal?.id &&
			other.group?.id == group?.id
	}

	int hashCode() {
		def builder = new HashCodeBuilder()
		if (principal) builder.append(principal.id)
		if (group) builder.append(group.id)
		builder.toHashCode()
	}

	static PrincipalGroup get(long principalId, long groupId) {
		find 'from PrincipalGroup where principal.id=:principalId and group.id=:groupId',
			[principalId: principalId, groupId: groupId]
	}

	static PrincipalGroup create(Principal principal, Group group, boolean flush = false) {
		new PrincipalGroup(principal: principal, group: group).save(flush: flush, insert: true)
	}

	static boolean remove(Principal principal, Group group, boolean flush = false) {
		PrincipalGroup instance = PrincipalGroup.findByPrincipalAndGroup(principal, group)
		instance ? instance.delete(flush: flush) : false
	}

	static void removeAll(Principal principal) {
		executeUpdate 'DELETE FROM PrincipalGroup WHERE principal=:principal', [principal: principal]
	}

	static void removeAll(Group group) {
		executeUpdate 'DELETE FROM PrincipalGroup WHERE group=:group', [group: group]
	}

	static mapping = {
		id composite: ['group', 'principal']
		version false
	}
}
